package org.jvm.util;

import org.jvm.rtda.Object;

import java.io.*;
import java.util.*;

/**
 * author : wangsixiang02
 * date : 2023/1/7
 * desc :
 */
public class JvmUtil {

    public static Map<String, String> primitiveTypes = new HashMap<String, String>() {
        {
            put("void", "V");
            put("boolean", "Z");
            put("byte", "B");
            put("short", "S");
            put("int", "I");
            put("long", "J");
            put("char", "C");
            put("float", "F");
            put("double", "D");
        }
    };

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    /**
     * 将java的String实例转换为jvm中使用的字符串
     *
     * @param javaString
     * @return
     */
    public static String javaStringToJvmString(Object javaString) {
        if (javaString == null) {
            return null;
        }
        Object charArrayObject = javaString.getRefVar("value", "[C");
        return new String(charArrayObject.chars());
    }

    public static String toDescriptor(String className) {
        if (className.charAt(0) == '[') {
            // array
            return className;
        }
        if (primitiveTypes.containsKey(className)) {
            // primitive
            return primitiveTypes.get(className);
        }
        // object
        return "L" + className + ";";
    }

    public static String toClassName(String descriptor) {
        if (descriptor.charAt(0) == '[') {
            // array
            return descriptor;
        }
        if (descriptor.charAt(0) == 'L') {
            // object
            return descriptor.substring(1, descriptor.length() - 1);
        }
        for (Map.Entry<String, String> entry : primitiveTypes.entrySet()) {
            if (entry.getValue().equals(descriptor)) {
                return entry.getKey();
            }
        }
        throw new RuntimeException("unkonw descriptor");
    }


    /**
     * 将基本类型进行包装
     *
     * @param val jvm的基本类型
     * @return java包装类
     */
    public static Object box(java.lang.Object val) {
        if (val instanceof Boolean) {

        }

        return null;
    }

}
